package com.vcit.common.core.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.sun.javafx.binding.StringFormatter;
import com.vcit.common.utils.vcitDianXin.MD5;
import com.vcit.common.utils.vcitDianXin.VcitSendSmsEntity;
import com.vcit.common.utils.vcitDianXin.client.Request;
import com.vcit.common.utils.vcitDianXin.client.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.vcit.common.core.service.ISmsService;
import com.vcit.common.utils.StringUtils;
import com.vcit.common.exception.ServiceException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 短信服务实现类
 */
@Service
public class SmsServiceImpl implements ISmsService {
    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Value("${sms.enabled:false}")
    private boolean smsEnabled;

    @Value("${sms.birthday.template}")
    private String birthdayTemplate;

    @Value("${sms.provider.type}")
    private String providerType;

    @Autowired
    private SmsProperties smsProperties;
    @Autowired
    private VcitSendSmsEntity sendSmsEntity;

    @Override
    public boolean sendSms(String phoneNumber, String content) {
        if (!smsEnabled) {
            log.info("短信服务未启用，模拟发送短信到{}，内容：{}", phoneNumber, content);
            return true;
        }

        validateSmsParams(phoneNumber, content);

        try {
            switch (providerType.toLowerCase()) {
                case "aliyun":
                    return sendAliyunSms(phoneNumber, content);
                case "tencent":
                    return sendTencentSms(phoneNumber, content);
                case "vcit":
                    return sendVcitSms(phoneNumber, content);
                default:
                    throw new ServiceException("不支持的短信服务提供商: " + providerType);
            }
        } catch (Exception e) {
            log.error("发送短信失败 - 手机号: {}, 错误信息: {}", phoneNumber, e.getMessage());
            return false;
        }
    }
    /**
     * {"appKey":"100819","timestamp":"1546589422955","mobile":"18695993557",
     * "content":"汉中市政府","spNumber":"","sendTime":"20190809090057","reportUrl":"",
     * "moUrl":"","attach":"","sign":"B65977B7BC6FF701A9B4395550CB3577"}
     * @return
     */
    private  VcitSendSmsEntity buildSendEntity(String phoneNumber,String name) {
        // TODO Auto-generated method stub

        sendSmsEntity.setTimestamp(System.currentTimeMillis()+"");
        sendSmsEntity.setMobile(phoneNumber);
        String content = StringUtils.format(birthdayTemplate, name);


        sendSmsEntity.setContent(content);
        //entity.setReportUrl("http://127.0.0.1:7801/test/callback");
        sendSmsEntity.setSpNumber("");
        //定时发送
        //entity.setSendTime("20190809090057");
        //签名校验必填写字段
        //appKey,timestamp,mobile,content,spNumber,sendTime,appSecret
        String source = sendSmsEntity.getAppKey() + sendSmsEntity.getTimestamp() + sendSmsEntity.getMobile() + sendSmsEntity.getContent()
                + sendSmsEntity.getSpNumber() + sendSmsEntity.getSendTime() +sendSmsEntity.getAppSecret();
        String sign = MD5.getMD5(source);
        sendSmsEntity.setSign(sign);
        return sendSmsEntity;
    }
    /**
     * vcit 短信发送
     * @param phoneNumber
     * @param userName
     * @return
     */
    private boolean sendVcitSms(String phoneNumber, String userName) {
        //1. 构建数据包对象
        VcitSendSmsEntity sendEntity = buildSendEntity(phoneNumber,userName);
        if (StringUtils.isEmpty(sendEntity.getAppKey())) {
            throw new ServiceException("vcit短信配置不完整");
        }
        // TODO: 实现vcit短信发送逻辑
        //2. 转化对象为json字符串数据
        String data =JSON.toJSONString(sendEntity);

        try {
            //3. 字符串url编码，防止特殊字符被客户端强行改变，譬如+会被浏览器或者其他客户端变更为空格
            String encodeData = URLEncoder.encode(data, "UTF-8");
            Request request = null;
            //4. 发送
            String url =sendEntity.getHttpServer()+sendEntity.getSmsSendUrl();

            request = Request.newHttpRequestBuilder().uri(url).timeout(5000).charset("utf-8").method(Request.POST)
                    .contentType(Request.ContentType.JSON).build();
           Response resp = request.send(sendEntity.getHttpServer()+sendEntity.getSmsSendUrl(), encodeData);
            request.release();
            //解析发送结果

            // 处理响应
            if (resp.status() == 200 && resp.content() != null) {
                JSONObject respJson = JSON.parseObject(resp.content());
                if (respJson.getInteger("status") == 1) {
                    log.info("vcit电信短信发送成功 - 手机号: {},请求ID: {}", phoneNumber,respJson.getLong("taskId"));
                    return true;
                }
                return false;
            } else {
                log.error("vcit电信短信发送成功 - 手机号: {}", phoneNumber);
                return false;
            }

        } catch (UnsupportedEncodingException e) {
            log.error("vcit短信发送异常 - 手机号: {}, 错误信息: {}", phoneNumber, e.getMessage());
            throw new ServiceException("短信发送失败: " + e.getMessage());
        }catch (Exception e) {
            log.error("vcit云短信发送异常 - 手机号: {}, 错误信息: {}", phoneNumber, e.getMessage());
            throw new ServiceException("短信发送失败: " + e.getMessage());
        }

    }

    @Override
    public boolean sendBirthdayWish(String phoneNumber, String userName) {
        if (StringUtils.isEmpty(userName)) {
            log.warn("发送生日祝福失败：用户名为空");
            return false;
        }

        try {
           // String content = StringUtils.format(birthdayTemplate, userName);
            boolean result = sendSms(phoneNumber, userName);
           // boolean result = sendSms(phoneNumber, content);
            if (result) {
                log.info("成功发送生日祝福短信给用户: {}", userName);
            }
            return result;
        } catch (Exception e) {
            log.error("发送生日祝福短信失败 - 用户: {}, 错误: {}", userName, e.getMessage());
            return false;
        }
    }

    /**
     * 验证手机号 短信模板 不能为空
     * @param phoneNumber
     * @param content
     */
    private void validateSmsParams(String phoneNumber, String content) {
        if (StringUtils.isEmpty(phoneNumber)) {
            throw new ServiceException("手机号不能为空");
        }
        if (StringUtils.isEmpty(content)) {
            throw new ServiceException("用户名不能为空");
        }
        /*if (!StringUtils.isMobile(phoneNumber)) {
            throw new ServiceException("无效的手机号格式");
        }*/
    }

    private boolean sendAliyunSms(String phoneNumber, String userName) {
        if (StringUtils.isEmpty(smsProperties.getAliyun().getAccessKeyId())) {
            throw new ServiceException("阿里云短信配置不完整");
        }
        // TODO: 实现阿里云短信发送逻辑

            try {
                // 配置阿里云客户端
                Config config = new Config()
                        .setAccessKeyId(smsProperties.getAliyun().getAccessKeyId())
                        .setAccessKeySecret(smsProperties.getAliyun().getAccessKeySecret())
                        .setEndpoint("dysmsapi.aliyuncs.com");

                // 创建API请求并设置参数
                Client client = new Client(config);
                SendSmsRequest request = new SendSmsRequest()
                        .setPhoneNumbers(phoneNumber)
                        .setSignName(smsProperties.getAliyun().getSignName())
                        .setTemplateCode(smsProperties.getAliyun().getTemplateCode())
                        .setTemplateParam("{\"name\":\"" + userName + "\"}");

                // 发送短信
                SendSmsResponse response = client.sendSms(request);

                // 处理响应
                if (response.getBody().getCode().equals("OK")) {
                    log.info("阿里云短信发送成功 - 手机号: {}, 请求ID: {}", phoneNumber, response.getBody().getRequestId());
                    return true;
                } else {
                    log.error("阿里云短信发送失败 - 手机号: {}, 错误码: {}, 错误信息: {}",
                            phoneNumber, response.getBody().getCode(), response.getBody().getMessage());
                    String errorCode = response.getBody().getCode();
                    String errorMessage = response.getBody().getMessage();
                    // 根据错误码给出具体提示
                    switch (errorCode) {
                        case "InvalidAccessKeyId":
                            log.error("AccessKey ID无效，请检查配置");
                            break;
                        case "SignatureDoesNotMatch":
                            log.error("AccessKey Secret无效，请检查配置");
                            break;
                        case "InvalidSignName":
                            log.error("短信签名无效或未审核通过");
                            break;
                        case "InvalidTemplateCode":
                            log.error("短信模板无效或未审核通过");
                            break;
                        case "InsufficientBalance":
                            log.error("短信服务余额不足");
                            break;
                        default:
                            log.error("短信发送失败: " + errorMessage);
                            break;
                    }
                    return false;
                }
            } catch (Exception e) {
                log.error("阿里云短信发送异常 - 手机号: {}, 错误信息: {}", phoneNumber, e.getMessage());
                throw new ServiceException("短信发送失败: " + e.getMessage());
            }



    }

    private boolean sendTencentSms(String phoneNumber, String content) {
        if (StringUtils.isEmpty(smsProperties.getTencent().getSecretId())) {
            throw new ServiceException("腾讯云短信配置不完整");
        }
        // TODO: 实现腾讯云短信发送逻辑
        log.info("通过腾讯云发送短信到{}", phoneNumber);
        return true;
    }
}

@Configuration
@ConfigurationProperties(prefix = "sms.provider")
class SmsProperties {
    private AliyunConfig aliyun = new AliyunConfig();
    private TencentConfig tencent = new TencentConfig();


    public static class AliyunConfig {
        private String accessKeyId;
        private String accessKeySecret;
        private String signName;
        private String templateCode;

        // getters and setters
        public String getAccessKeyId() { return accessKeyId; }
        public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; }
        public String getAccessKeySecret() { return accessKeySecret; }
        public void setAccessKeySecret(String accessKeySecret) { this.accessKeySecret = accessKeySecret; }
        public String getSignName() { return signName; }
        public void setSignName(String signName) { this.signName = signName; }
        public String getTemplateCode() { return templateCode; }
        public void setTemplateCode(String templateCode) { this.templateCode = templateCode; }
    }

    public static class TencentConfig {
        private String secretId;
        private String secretKey;
        private String sdkAppId;
        private String signName;
        private String templateId;

        // getters and setters
        public String getSecretId() { return secretId; }
        public void setSecretId(String secretId) { this.secretId = secretId; }
        public String getSecretKey() { return secretKey; }
        public void setSecretKey(String secretKey) { this.secretKey = secretKey; }
        public String getSdkAppId() { return sdkAppId; }
        public void setSdkAppId(String sdkAppId) { this.sdkAppId = sdkAppId; }
        public String getSignName() { return signName; }
        public void setSignName(String signName) { this.signName = signName; }
        public String getTemplateId() { return templateId; }
        public void setTemplateId(String templateId) { this.templateId = templateId; }
    }

    // getters and setters
    public AliyunConfig getAliyun() { return aliyun; }
    public void setAliyun(AliyunConfig aliyun) { this.aliyun = aliyun; }
    public TencentConfig getTencent() { return tencent; }
    public void setTencent(TencentConfig tencent) { this.tencent = tencent; }
} 
